package com.es.www.transaction.aspect;

import java.sql.Connection;
import java.sql.SQLException;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.es.www.transaction.util.JdbcUtil;

/**
 * @Created by michangtao
 * @Date 2022/2/9 17:14
 * @Description
 */
@Component
@Aspect
public class TransactionAspect {


    @Pointcut("@annotation(com.es.www.transaction.aspect.TransactionControl)")
    public void transactionPoint(){

    }


    @Around(value = "transactionPoint()")
    public Object proceed(ProceedingJoinPoint joinPoint) throws Throwable {
        Connection connection = JdbcUtil.getConnection();
        //开启事务
        connection.setAutoCommit(false);
        try {
            Object retval = joinPoint.proceed();
            //方法执行完成之后提交事务
            connection.commit();
            return retval;
        }
        catch (Exception e) {
            connection.rollback();
            e.printStackTrace();
            throw e;
        }finally {
            JdbcUtil.removeConnection();
        }

    }

}
